import os
import stat
import sys
import user
import errno

def main():
    path = sys.argv[1]
    mode = sys.argv[2]
    try:
        if validate_permission(path, mode):
            print "Permission is valid"
        else:
            print "Permission invalid"
    except OSError, ex:
        print ex.strerror
    try:
        if validate_is_dir(path):
            print 'This is directory'
        else:
            print 'This is not directory'
    except OSError, ex:
        print ex.strerror

def process_dir(path,username, groupname, mode):
    try:
        if validate_is_dir(path):
            if not validate_permission(path,mode):
                set_permission(path,mode)
            if not validate_owner(path,username,groupname):
                set_owner(path, username, groupname)
    except OSError, ex:
        if ex.errno == errno.ENOENT:
            if create_dir(path,mode):
                status = set_owner(path,username,groupname)
        return status

def validate_permission(path, mode):
    statinfo = os.stat(path)
    if stat.S_IMODE(statinfo.st_mode) == int(str(mode),8):
        return True
    else:
        return False

def set_permission(path,mode):
    try:
        os.chmod(path,int(str(mode),8))
        return True
    except:
        return False

def validate_owner(path,username,groupname):
    statinfo = os.stat(path)
    if ((statinfo.st_uid == user.get_user_id(username)) or (statinfo.st_gid == user.get_group_id(groupname))):
        return True
    else:
        return False

def set_owner(path,username,groupname):
    try:
        os.chown(path,user.get_user_id(username),user.get_group_id(groupname))
        return True
    except:
        return False

def validate_is_dir(path):
    statinfo = os.stat(path)
    if stat.S_ISDIR(statinfo.st_mode):
        return True
    else:
        return False

def create_dir(path, mode):
    try:
        os.mkdir(path,int(str(mode),8))
        return True
    except:
        return False

if __name__ == "__main__":
        main()
